import Router from '@koa/router';
import passport from 'koa-passport';
import jwt from 'jsonwebtoken';
import dotenv from 'dotenv';
import User from '../models/User';

dotenv.config();

const router = new Router();

router.get('/login', async (ctx) => {
  if (ctx.isAuthenticated()) {
    return ctx.redirect('/profile');
  }
  await ctx.render('login');
});

router.get('/register', async (ctx) => {
  await ctx.render('register');
});

router.post('/register', async (ctx) => {
  const { username, password } = ctx.request.body as any;
  try {
    const user = await User.create({ username, password });
    await ctx.login(user);
    ctx.redirect('/profile');
  } catch (error) {
    ctx.status = 400;
    ctx.body = { message: 'Registration failed', error };
  }
});

router.post('/login', passport.authenticate('local', {
  successRedirect: '/profile',
  failureRedirect: '/login',
  failWithError: true
}));

router.post('/logout', (ctx) => {
  ctx.logout();
  ctx.redirect('/login');
});

router.get('/profile', async (ctx) => {
  if (ctx.isAuthenticated()) {
    await ctx.render('profile', { user: ctx.state.user });
  } else {
    ctx.redirect('/login');
  }
});

router.get('/auth/github', passport.authenticate('github', { scope: ['user:email'] }));

router.get('/auth/github/callback', passport.authenticate('github', { failureRedirect: '/login' }), (ctx) => {
  ctx.redirect('/profile');
});

router.post('/login-jwt', (ctx, next) => {
  return passport.authenticate('local', { session: false }, (err: any, user: any) => {
    if (err || !user) {
      ctx.status = 401;
      ctx.body = { message: 'Authentication failed' };
      return;
    }
    const payload = { id: user.id, username: user.username };
    const token = jwt.sign(payload, process.env.JWT_SECRET as string, { expiresIn: '1h' });
    ctx.body = { message: 'Login successful', token: `Bearer ${token}` };
  })(ctx, next);
});

router.get('/profile-jwt', passport.authenticate('jwt', { session: false }), (ctx) => {
  ctx.body = { user: ctx.state.user };
});

export default router;